<template>
  <div class="tableList">
    <div class="onlyTable">
      <vxe-grid
        ref="table"
        class="table-tree"
        resizable
        show-overflow
        row-key
        keep-source
        size="small"
        border
        :data="transTableData"
        height="auto"
        :columns="columns"
        :tree-config="{
          line: true,
          transform: true,
          parentField: 'parentTag',
          children: 'paramList',
          rowField: 'tag',
          iconOpen: '',
          iconClose: 'vxe-icon-square-plus',
        }"
        v-bind="isEdit ? vxeOptions : null"
        @edit-actived="editActivedEvent"
      >
        <template #d_itemName="{ row }">
          <template v-if="!row.parentTag">
            <i :class="$refs.table.isTreeExpandByRow(row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
          </template>
          <template v-else>
            <i class="vxe-circle"></i>
          </template>
          <span>{{ !row.parentTag ? row.itemName : row.paramName }}</span>
        </template>
        <template #e_itemName="scope">
          <template v-if="!scope.row.parentTag">
            <i :class="$refs.table.isTreeExpandByRow(scope.row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
          </template>
          <template v-else>
            <i class="vxe-circle"></i>
          </template>
          <vxe-input v-if="!scope.row.parentTag" v-model="scope.row.itemName" type="text"></vxe-input>
          <vxe-input v-else v-model="scope.row.paramName" type="text"></vxe-input>
        </template>
        <template #e_itemShortName="scope">
          <vxe-input v-model="scope.row.itemShortName" :disabled="!isdisabled" type="text"></vxe-input>
        </template>
        <template #d_itemShortName="{ row }">
          <span>{{ row.itemShortName }}</span>
        </template>
        <template #d_salesUnit="{ row }">
          <span>{{ row.salesUnit }}</span>
        </template>
        <template #e_salesUnit="scope">
          <vxe-input v-model="scope.row.salesUnit" :disabled="isdisabled" type="text"></vxe-input>
        </template>
        <template #d_unitPrice="{ row }">
          <span>{{ row.unitPrice }}</span>
        </template>
        <template #e_unitPrice="scope">
          <vxe-input v-model="scope.row.unitPrice" :disabled="isdisabled" type="text"></vxe-input>
        </template>
        <template #d_std="scope">
          <span>{{ scope.row.detectionStdList | formatDetectionStd }}</span>
        </template>
        <template #e_std="scope">
          <vxe-input
            :value="scope.row.detectionStdList | formatDetectionStd"
            :disabled="isdisabled"
            type="text"
            readonly
            clearable
            @clear="clearDetectionStdList(scope.row)"
            @click="openDetectionStd(scope.row)"
          ></vxe-input>
        </template>
        <template #d_area="{ row }">
          <span>{{ row.domainIds | formatDetectionDomain(domainList) }}</span>
        </template>
        <template #e_area="{ row }">
          <vxe-select v-model="row.domainIds" placeholder="检测领域" :disabled="isdisabled" multiple clearable>
            <vxe-option v-for="item in domainList" :key="item.id" :value="item.id" :label="item.dictValue"></vxe-option>
          </vxe-select>
        </template>
        <!-- <template #d_hours="{ row }">
        <span>{{ row.workingHours }}</span>
      </template> -->
        <template #e_workingHours="scope">
          <vxe-input v-model="scope.row.workingHours" :disabled="isdisabled" type="text"></vxe-input>
        </template>
        <!-- <template #d_remark="{ row }">
        <span>{{ row.remarks }}</span>
      </template> -->
        <template #e_remarks="scope">
          <vxe-input v-model="scope.row.remarks" :disabled="isdisabled" type="text"></vxe-input>
        </template>
        <template #d_status="{ row }">
          <span>{{ row.isEnabled | formatStatus }}</span>
        </template>
        <template #e_status="scope">
          <vxe-select v-model="scope.row.isEnabled" placeholder="状态" clearable @change="changeEnabled(scope.row)">
            <vxe-option :value="true" label="启用"></vxe-option>
            <vxe-option :value="false" label="停用"></vxe-option>
          </vxe-select>
        </template>

        <template #operation="{ row }">
          <vxe-button v-if="!row.parentTag" type="text" status="primary" @click="add(row, 'bottom')"
            >添加检测参数</vxe-button
          >
          <vxe-button type="text" status="danger" @click="del(row)">删除</vxe-button>
        </template>
      </vxe-grid>
    </div>
    <SelectStd
      ref="selectStd"
      v-model="curRow.detectionStdList"
      :tableData="stdList"
      :total="stdTotal"
      :columns="stdColumn"
      title="选择检测标准"
      :searchConfig="searchConfig"
      @pager="userPager"
      @search="getStdList"
      @submit="selStd"
    />
  </div>
</template>
<script>
import Sortable from 'sortablejs';
import XEUtils from 'xe-utils';
import VXETable from 'vxe-table';
import SelectStd from '/@/components/SelectFromTableDialog';

export default {
  components: { SelectStd },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    columns: {
      type: Array,
      default: () => [],
    },
    tableData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    const nameValid = ({ row, cellValue }) => {
      if (!row.parentTag) {
        if (!row.itemName) {
          return new Error('检测项目名不能为空');
        }
      } else {
        if (!row.paramName) {
          return new Error('检测参数不能为空');
        }
      }
    };
    const salesUnitValid = ({ row, cellValue }) => {
      if (!!row.parentTag && !row.salesUnit) {
        return new Error('计价单位不能为空');
      }
    };
    const domainIdsValid = ({ row, cellValue }) => {
      if (!!row.parentTag && !row.domainIds) {
        return new Error('检测领域不能为空');
      }
    };
    const itemShortNameValid = ({ row, cellValue }) => {
      if (!row.parentTag && !row.itemShortName) {
        return new Error('项目编号拼音简称不能为空');
      }
    };
    const validRules = {
      name: [{ required: true, validator: nameValid }],
      salesUnit: [{ required: true, validator: salesUnitValid }],
      domainIds: [{ required: true, validator: domainIdsValid }],
      itemShortName: [{ required: true, validator: itemShortNameValid }],
    };
    return {
      dialogVisible: false,
      showEdit: false,
      isEnabledFlag: false,
      isdisabled: false,
      searchConfig: [
        {
          label: '检测标准名称',
          field: 'dictValue',
        },
      ],
      types: [
        {
          name: '项目商务状态档案',
        },
      ],
      vxeOptions: {
        'row-config': { isHover: true, isCurrent: true },
        'radio-config': { labelField: 'groupName' },
        'scroll-y': { enabled: false },
        'edit-rules': validRules,
        'edit-config': {
          trigger: 'click',
          mode: 'row',
          showStatus: true,
          showIcon: false,
        },
      },
      selectRow: null,
      domainList: [],
      stdList: [],
      exportTableData: [],
      mergeCells: [],
      total: null,
      stdColumn: [
        {
          type: 'checkbox',
          title: '',
          width: 60,
          editRender: {},
        },
        {
          field: 'dictValue',
          title: '检测标准',
          editRender: {},
        },
      ],
      stdTotal: 0,
      curRow: {
        detectionStdList: [],
      },
    };
  },
  filters: {
    formatStatus(val) {
      return val ? '启用' : '停用';
    },
    formatDetectionStd(stdList) {
      if (!stdList) return;
      return stdList.map((item) => item.dictValue).join('、');
    },
    formatDetectionDomain(val, stdList) {
      if (!val) return;
      const list = stdList.filter((item) => val.includes(item.id));
      return list.map((item) => item.dictValue).join('、');
    },
  },
  computed: {
    transTableData() {
      function flatten(arr = [], parent = null) {
        return arr.reduce(function (prev, item) {
          item.tag = item.id;
          item.parentTag = parent?.id;
          if (!parent) {
            item.itemId = item.id;
          } else {
            item.paramId = item.id;
          }
          item.detectionStdList = Array.isArray(item.detectionStdList) ? item.detectionStdList : [];
          item.detectionStdIds = item.detectionStdList?.map((item) => item.id);
          item.domainIds = Array.isArray(item.domainIds) ? item.domainIds : item.domainIds?.split(',');
          return prev.concat(item, flatten(item.chargeStdParamList || [], item));
        }, []);
      }
      return flatten(this.tableData);
    },
  },
  created() {
    this.getStdList();
    this.getDomainList();
  },
  mounted() {},
  methods: {
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      if (!query) {
        query = window.location.hash.split('?')[1];
      }
      if (!query) {
        return;
      }
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) {
          return decodeURIComponent(pair[1]);
        }
      }
      return '';
    },
    editActivedEvent({ row, rowIndex }) {
      this.isdisabled = !row.parentTag;
    },
    openDetectionStd(row) {
      this.curRow = row;
      this.$refs.selectStd.dialogVisible = true;
    },
    getStdList(params = { page: 1, size: 10 }) {
      this.$api.getStdList({ ...params, isEnabled: true }).then((res) => {
        const { list, total } = res.data;
        this.stdList = list;
        this.stdTotal = total;
      });
    },
    getDomainList(params = { page: 1, size: 10 }) {
      this.$api.getDomainList({ ...params, isEnabled: true }).then((res) => {
        const { list } = res.data;
        this.domainList = list;
      });
    },
    changeEnabled(row) {
      !row.parentTag &&
        row.chargeStdParamList.forEach((item) => {
          if (!row.isEnabled) {
            item.isEnabled = row.isEnabled;
          }
        });
    },
    editEvent(row) {
      this.selectRow = row;
      this.showEdit = true;
    },
    async add(currRow, locat) {
      const $table = this.$refs.table;
      const record = {
        tag: Date.now() + '',
        parentTag: currRow.tag,
        paramName: '',
        salesUnit: '',
        unitPrice: '',
        detectionStdIds: [],
        standard: '',
        workingHours: '',
        remarks: '',
        isEnabled: true,
      };

      const { row: newRow } = await $table.insertAt(record, -1);
      // console.log(currRow.chargeStdParamList, 111);
      // currRow.chargeStdParamList.push(newRow);
      await $table.setTreeExpand(currRow, true); // 将父节点展开
      await $table.setActiveRow(newRow); // 插入子节点
    },
    selStd(params) {
      this.curRow.detectionStdList = params || [];
      this.curRow.detectionStdIds = params.map((item) => item.id) || [];
      this.$refs.selectStd.dialogVisible = false;
    },
    clearDetectionStdList(row) {
      row.detectionStdList = [];
    },
    userPager(params) {
      this.getStdList(params);
    },
    async del(row) {
      const $table = this.$refs.table;
      await $table.remove(row);
    },
    submit() {
      const { field, groupName } = this.$refs.tableOperation.getCurrentRecord();
      this.selectRow.operationField = field;
      this.selectRow.groupName = groupName;
      this.showEdit = false;
    },
    async fullValidEvent() {
      const $table = this.$refs.table;
      const errMap = await $table.fullValidate().catch((errMap) => errMap);
      if (errMap) {
        const msgList = [];
        Object.values(errMap).forEach((errList) => {
          errList.forEach((params) => {
            const { rowIndex, column, rules } = params;
            rules.forEach((rule) => {
              msgList.push(`校验错误：${rule.message}`);
            });
          });
        });
        VXETable.modal.message({
          status: 'error',
          slots: {
            default() {
              return [
                <div class="red" style="max-height: 400px;overflow: auto;">
                  {msgList.map((msg) => (
                    <div>{msg}</div>
                  ))}
                </div>,
              ];
            },
          },
        });
      } else {
        VXETable.modal.message({ status: 'success', content: '校验成功！' });
        this.$emit('submit');
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.onlyTable {
  height: calc(100% - 20px) !important;
}
</style>
